﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;

namespace Fast.Framework.Logging
{

    /// <summary>
    /// 文件日志主机服务
    /// </summary>
    internal class FileLogHostService : BackgroundService
    {

        /// <summary>
        /// 配置
        /// </summary>
        private readonly IConfiguration configuration;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="configuration">配置</param>
        public FileLogHostService(IConfiguration configuration)
        {
            this.configuration = configuration;
        }

        /// <summary>
        /// 执行异步
        /// </summary>
        /// <param name="stoppingToken">停止令牌</param>
        /// <returns></returns>
        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            return Task.Run(async () =>
            {
                while (!stoppingToken.IsCancellationRequested)
                {
                    var fileCount = Convert.ToInt32(configuration.GetSection("Logging:FileLog:MaxFileCount").Value);
                    if (fileCount > 0)
                    {
                        foreach (var directory in FileHelper.GetDirectorys())
                        {
                            var directoryInfo = new DirectoryInfo(directory);
                            var fileInfos = directoryInfo.GetFiles();

                            if (fileInfos.Length > fileCount)
                            {
                                var removeFileInfo = fileInfos.OrderBy(o => o.CreationTime).ThenBy(o => o.LastWriteTime).SkipLast(fileCount).ToList();
                                foreach (var item in removeFileInfo)
                                {
                                    FileHelper.Remove(item.FullName);//如果流已占用关闭流再删除
                                    File.Delete(item.FullName);
                                }
                            }
                        }
                    }
                    else
                    {
                        await Task.Delay(1800000, stoppingToken);//没有配置最大文件个数 默认30分钟 进入下一次循环
                    }
                    var autolearDelay = Convert.ToInt32(configuration.GetSection("Logging:FileLog:AutolearDelay").Value);
                    await Task.Delay(autolearDelay > 0 ? autolearDelay : 600000, stoppingToken);//默认10分钟清理一次文件
                }
            }, stoppingToken);
        }
    }
}
